package com.dalitek.sampleface.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class CameraDetectView extends View {
    private static final String TAG = "CameraDetectView";

    public CameraDetectView(Context context) {
        super(context);
    }
    public CameraDetectView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public CameraDetectView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private Paint paint ;
    private int frameWidth;
    private int frameHeight;
    private int viewWidth;
    private int viewHeight;
    public void init(int frameWidth, int frameHeight, int viewWidth, int viewHeight,int scaleX) {
        paint = new Paint();
        this.frameWidth = frameWidth;
        this.frameHeight = frameHeight;
        this.viewWidth = viewWidth;
        this.viewHeight = viewHeight;

        //摄像头画面是镜像，配合TextureView设置的android:scaleX="-1" 调整人脸框和摄像头画面
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2.0f);
        setScaleX(scaleX);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for(OverlayEntity overlayEntity : overlayEntityList){
            if (overlayEntity == null || overlayEntity.getRect() ==null) continue;
            //根据承载view视图大小和摄像头播放大小比例计算人脸框宽高
            Rect rect = overlayEntity.getRect();
            rect.left = rect.left * viewWidth / frameWidth;
            rect.right = rect.right * viewWidth / frameWidth;
            rect.top = rect.top * viewHeight / frameHeight;
            rect.bottom = rect.bottom * viewHeight / frameHeight;

            paint.setColor(overlayEntity.getPaintColor());
            canvas.drawRect(rect,paint);
        }
    }

    private List<OverlayEntity> overlayEntityList = new ArrayList<>();

    public synchronized void setValue(List<OverlayEntity> overlayEntityList) {
        this.overlayEntityList.clear();
        this.overlayEntityList.addAll(overlayEntityList);
    }
}